package com.axjy.comm.util;

import com.axjy.comm.vo.Result;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.data.redis.core.BoundValueOperations;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;
import java.util.concurrent.TimeUnit;

@Component
public class AuthInterceptor implements HandlerInterceptor {

    @Resource
    private TokenUtil tokenUtil;

    @Resource
    private StringRedisTemplate stringRedisTemplate;


    /**
     * 1. 判断请求路径是否有/p/, 有通过，无验证
     * 2. 验证token是有有效
     * 3. token是否过期
     * 4. token续命
     * @param request
     * @param response
     * @param handler
     * @return
     * @throws Exception
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        System.out.println("----------进入拦截器");
        String uri= request.getRequestURI();
         response.setContentType("application/json;charset=UTF-8");

         boolean flag=uri.contains("/p/");
         if(flag==true){
             return true;  //不需要登录情况
         }
         //后面的代码需要登录的情况
         String token= request.getHeader("token");
         if(token==null){
             Result result=Result.fail("5000","必须登录才能访问！");
             ObjectMapper objectMapper=new ObjectMapper();
             String json=objectMapper.writeValueAsString(request);
             PrintWriter out= response.getWriter();
             out.print(json);
             out.close();
            return false;
         }else{
            Integer userId= tokenUtil.checkToken(token);
            if(userId.equals(-1)){
                Result result=Result.fail("5001","token不正确！");
                ObjectMapper objectMapper=new ObjectMapper();
                String json=objectMapper.writeValueAsString(request);
                PrintWriter out= response.getWriter();
                out.print(json);
                out.close();
                return false;
            }else{
                System.out.println("--userId不是-1的情况---"+userId);
                BoundValueOperations<String,String> operations= stringRedisTemplate.boundValueOps("token:"+userId);
                String value=operations.getKey();
                if(value==null){
                    Result result=Result.fail("5001","token过期！");
                    ObjectMapper objectMapper=new ObjectMapper();
                    String json=objectMapper.writeValueAsString(request);
                    PrintWriter out= response.getWriter();
                    out.print(json);
                    out.close();
                    return false;
                }else {
                    System.out.println("--拦截器-->"+userId);
                    TpContext.setLoginUserTl(userId);
                    System.out.println("-------->end");
                    //token续期, 暂时连接不上
                    //operations.expire(tokenUtil.getTtl(), TimeUnit.MINUTES);
                    return true;
                }
            }


         }


    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        TpContext.removeLoginUserTl();
    }
}
